/**
 * 专门用来处理历史记录相关的接口
 */

const express = require('express')
const util = require('util')
const historyRouter = express.Router()

const {
  insertUserHistorySql,
  selectUserLastRecoreSql,
  updateUserHistorySql,
  selectCreatedHistorySql,
  deleteUserHistoryByIdSql,
  deleteUserHistoryByIdsSql
} = require('../sql/history')

// 引入 db 文件
const { db } = require('../utils/db')
const { log } = require('console')

// 将db.query转换为返回Promise的函数
const queryPromise = util.promisify(db.query).bind(db)

// 定义一个函数用于计算持续时间
const calculateContinuousTime = (startTime, endTime) => {
  const start = new Date(startTime)
  const end = new Date(endTime)
  const durationInSeconds = Math.floor((end.getTime() - start.getTime()) / 1000)
  const minutes = Math.floor(durationInSeconds / 60)
  const seconds = durationInSeconds % 60

  // 格式化为 MM:SS
  const formattedMinutes = minutes.toString().padStart(2, '0')
  const formattedSeconds = seconds.toString().padStart(2, '0')

  return `${formattedMinutes}:${formattedSeconds}`
}

// 将 MM:SS 格式的时间转换为总秒数
const timeToSeconds = time => {
  const [minutes, seconds] = time.split(':').map(Number)
  return minutes * 60 + seconds
}

// 将总秒数转换回 MM:SS 格式
const secondsToTime = seconds => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds
    .toString()
    .padStart(2, '0')}`
}

// 累加两个 MM:SS 格式的时间字符串
const addTimes = (time1, time2) => {
  const totalSeconds = timeToSeconds(time1) + timeToSeconds(time2)
  return secondsToTime(totalSeconds)
}

// 定义一个函数用于插入数据
const insertData = async (
  mRoomId,
  roomId,
  MID,
  title,
  type,
  startTime,
  endTime,
  continuousTime,
  host
) => {
  await queryPromise(insertUserHistorySql, [
    parseInt(mRoomId),
    parseInt(roomId),
    parseInt(MID),
    title,
    type,
    startTime,
    // 这里的 nearTime 就是 startTime
    startTime,
    endTime,
    continuousTime,
    host
  ])
}

// 添加历史记录
historyRouter.post('/history/add', async (req, res) => {
  try {
    // 解构出需要的字段
    /**
     * mRoomId : 自己房间id
     * roomId : 参加房间id
     * MID : 参加房间哪个时间段id
     */
    const {
      mRoomId,
      roomId,
      MID,
      title,
      type,
      startTime,
      endTime,
      nearTime,
      host
    } = req.body

    // 查询最后一条历史记录
    const lastHistory = await queryPromise(selectUserLastRecoreSql, [
      parseInt(mRoomId)
    ])
    // 判断 lastHistory 是否为空
    if (lastHistory == 0) {
      // 为空说明是第一次添加历史记录
      const continuousTime = calculateContinuousTime(startTime, endTime)

      // 插入数据
      await insertData(
        mRoomId,
        roomId,
        MID,
        title,
        type,
        startTime,
        endTime,
        continuousTime,
        host
      )
    } else {
      // 不为空就是有数据
      // 有数据需要去判断 roomId 和 MID 是否一致
      console.log(lastHistory, roomId, MID)
      if (lastHistory[0].roomId == roomId && lastHistory[0].MID == MID) {
        // 如果一样，需要去执行更新操作
        // 先保存旧的持续时间
        const o_continuousTime = lastHistory[0].continuousTime
        // 再去计算出新的持续时间
        let continuousTime = calculateContinuousTime(startTime, endTime)

        // 在把两个时间相加
        continuousTime = addTimes(o_continuousTime, continuousTime)

        // 执行更新操作
        await queryPromise(updateUserHistorySql, [
          parseInt(mRoomId),
          nearTime,
          endTime,
          continuousTime,
          roomId,
          MID
        ])
      } else {
        //  如果不一样
        const continuousTime = calculateContinuousTime(startTime, endTime)
        // 插入数据
        await insertData(
          mRoomId,
          roomId,
          MID,
          title,
          type,
          startTime,
          endTime,
          continuousTime,
          host
        )
      }
    }

    res.status(200).json({
      code: 200,
      msg: '添加成功',
      data: {}
    })
  } catch (error) {
    console.log(error)
    res.status(500).json({ error: '添加失败' })
  }
})

// 查询历史记录
historyRouter.get('/history/getAllByType', async (req, res) => {
  try {
    const { roomId, type } = req.query
    const historyList = await queryPromise(selectCreatedHistorySql, [
      parseInt(roomId),
      type
    ])
    res.status(200).json({
      code: 200,
      msg: '查询成功',
      data: {
        historyList
      }
    })
  } catch (error) {
    console.log(error)
    res.status(500).json({ error: '查询失败' })
  }
})

// 删除历史记录
historyRouter.delete('/history/deleteHistory', async (req, res) => {
  try {
    const { roomId, id } = req.body
    // 判断id的长度去执行不同的sql语句
    if (id.length === 1) {
      await queryPromise(deleteUserHistoryByIdSql, [parseInt(roomId), id[0]])
    } else {
      const sql = deleteUserHistoryByIdsSql(id)
      await queryPromise(sql, [parseInt(roomId), ...id])
    }
    res.status(200).json({
      code: 200,
      msg: '删除成功',
      data: {}
    })
  } catch (error) {
    console.log(error)
    res.status(500).json({ error: '删除失败' })
  }
})

module.exports = historyRouter
